<template>
  <div>
    <div class="search_box">
      <el-form :inline="true" label-width="100px" :model="formData">
        <el-form-item label="小程序Appid">
          <el-input
            v-model="formData.appId"
            placeholder="小程序Appid"
            clearable
          />
        </el-form-item>
        <el-form-item label="小程序名称">
          <el-input
            v-model="formData.appName"
            placeholder="小程序名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="小程序类型">
          <el-select v-model="formData.appType" placeholder="请选择" clearable>
            <el-option label="微信" value="wx" />
            <el-option label="抖音" value="dy" />
            <el-option label="快手" value="ks" />
          </el-select>
        </el-form-item>
        <el-form-item label="分销商">
          <el-select
            v-model="formData.tenantId"
            filterable
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in tenantOption"
              :key="item?.id"
              :label="item.label"
              :value="item?.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="小程序状态">
          <el-select v-model="formData.status" placeholder="请选择" clearable>
            <el-option label="停用" :value="0" />
            <el-option label="启用" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getList(1)">查 询</el-button>
          <!-- v-auth="'api:agent:apps:search'" -->
          <el-button type="primary" @click="resetList">重 置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table_box_wrapper">
      <div style="margin: 0 0 0 12px">
        <el-button type="primary" @click="addApps">
          <el-icon style="margin-right: 5px">
            <Plus />
          </el-icon>
          新 增
        </el-button>
      </div>
      <!-- <div class="allocation_app">
        <el-button
          type="primary"
          :disabled="isDisabled"
          @click="handleAllocation('分销商')"
          v-auth="'api:agent:apps:setAgentApp'"
        >
          分配分销商小程序
        </el-button>
        <el-button
          type="primary"
          :disabled="isDisabled"
          @click="handleAllocation('用户')"
          v-auth="'api:agent:apps:setUserApp'"
        >
          分配用户小程序
        </el-button>
      </div> -->
      <custom-table
        :loading="loading"
        :columns="columns"
        :tableData="tableData"
        :pageObj="pageObj"
        @sizechange="sizechange"
        @currentChange="currentChange"
        class="table_box"
      >
        <!-- :typeSelect="true"
        @selectionChange="selectionChange" -->

        <!-- v-auth="'api:agent:apps:update'" -->
        <!-- <template #status="{ scope }">
          <el-tag v-if="scope.row?.status" type="success">启用</el-tag>
          <el-tag v-else type="danger">禁用</el-tag>
        </template> -->
        <template #status="{ scope }">
          <el-switch
            style="

--el-switch-on-color: #13ce66"
            :modelValue="scope.row.status === 1"
            inline-prompt
            active-text="启用"
            inactive-text="禁用"
            @click.stop="handleStatus(scope.row)"
          />
        </template>
        <template #operator="{ scope }">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button
            :type="scope.row?.owningTenant ? 'warning' : 'primary'"
            size="small"
            @click="handleActive(scope.row)"
          >
            {{ `${scope.row.owningTenant ? "解绑" : "分配"}` }}
          </el-button>
        </template>
      </custom-table>
    </div>

    <!-- 新增编辑信息 -->
    <info ref="infoRef" @success="getList(1)" />

    <!-- 分配小程序 -->
    <distributor ref="distributorRef" @success="getList(1)" :typePower="1" />
  </div>
</template>

<script setup lang="ts">
import customTable from "@/components/CustomTable/index.vue";
import distributor from "@/components/Distributor/index.vue";
import info from "./components/info.vue";
import { getAppsList, updateAppStatus } from "@/api/operateCenter/apps/index";
import { getAgentList } from "@/api/auth/index";
import { deleteBindApp } from "@/api/operateCenter/distributor/index";

import { reactive, ref } from "vue";
import { Plus } from "@element-plus/icons-vue";
import type { Action } from "element-plus";

const loading = ref<boolean>(false);
const tableData = ref<Array<any>>([]);
const selectionData = ref<Array<any>>([]);
const tenantOption = ref<Array<any>>([]);
const form = {
  appId: "",
  appType: "",
  appName: "",
  tenantId: undefined,
  status: undefined,
  pageNo: 1,
  pageSize: 10,
};

const formData = reactive(Object.assign({}, form));
interface modelPage {
  pageNo: number;
  pageSize: number;
  total: number;
}
const pageObj = reactive<modelPage>({
  pageNo: 1,
  pageSize: 10,
  total: 0,
});

const columns = reactive([
  { prop: "id", label: "Id", minWidth: 80 },
  { prop: "appId", label: "小程序AppId", minWidth: 160 },
  { prop: "appName", label: "小程序名称", minWidth: 140 },
  {
    prop: "appType",
    label: "小程序类型",
    minWidth: 100,
    formatter: (row: Record<string, any>) => {
      return row.appType === "wx"
        ? "微信小程序"
        : row.appType === "dy"
        ? "抖音小程序"
        : "";
    },
  },
  {
    prop: "owningTenant",
    label: "分销商",
    minWidth: 120,
    formatter: (row) => {
      return row?.owningTenant?.tenantName || "";
    },
  },
  { prop: "company", label: "公司主体", minWidth: 220 },
  { prop: "pathIndex", label: "小程序首页路径", minWidth: 180 },
  { prop: "status", slotName: "status", label: "小程序状态", minWidth: 100 },
  // { prop: "appGhId", label: "小程序原始Id", minWidth: 150 },
  { prop: "operator", slotName: "operator", label: "操作", width: 150 },
]);

const isDisabled = computed(() => {
  return selectionData.value.length > 0 ? false : true;
});

// 分配小程序
const distributorRef = ref();
const handleActive = (data: Record<string, any>) => {
  if (!data?.owningTenant) {
    distributorRef.value.showDialog(data);
  } else {
    ElMessageBox.alert("确定要解除小程序跟分销商的绑定吗？", "提醒", {
      confirmButtonText: "确定",
      callback: (action: Action) => {
        if (action === "confirm") {
          let params = {
            tenantId: data?.owningTenant.tenantId,
            appId: data.id,
          };
          deleteBindApp(params).then(() => {
            ElMessage.success("解绑成功");
            getList(1);
          });
        }
      },
    });
  }
};

const getList = (val = 0) => {
  // if (!val) {
  //   formData.pageNo = pageObj.pageNo;
  //   formData.pageSize = pageObj.pageSize;
  // } else {
  //   formData.pageNo = pageObj.pageNo = val === 1 ? val : 1;
  //   formData.pageSize = pageObj.pageSize = val === 1 ? 10 : pageObj.pageSize;
  // }
  formData.pageNo = pageObj.pageNo;
  formData.pageSize = pageObj.pageSize;

  formData.tenantId = formData.tenantId === "" ? undefined : formData.tenantId;
  formData.status = formData.status === "" ? undefined : formData.status;
  loading.value = true;
  getAppsList(formData)
    .then((res: Record<string, any>) => {
      tableData.value = res.data;
      pageObj.total = Number(res?.total);
    })
    .finally(() => {
      loading.value = false;
    });
};

// 重置
const resetList = () => {
  Object.assign(formData, form);
  getList(1);
};

// 新增
const infoRef = ref();
const addApps = () => {
  infoRef.value.showDialog();
};
// 编辑
const handleEdit = (val: Record<string, any>) => {
  infoRef.value.showDialog(val);
};

// 启用禁用
const handleStatus = (val: Record<string, any>) => {
  ElMessageBox.alert(
    `确定要${val?.status == 1 ? "禁用" : "启用"} "${val?.appName}" 小程序吗？`,
    "提醒",
    {
      confirmButtonText: "确定",
      callback: (action: Action) => {
        if (action == "confirm") {
          let params = {
            appId: val?.id,
            status: val?.status === 1 ? 0 : 1,
          };
          updateAppStatus(params).then(() => {
            ElMessage.success(`${val?.status ? "禁用" : "启用"}成功`);
            getList(1);
          });
        }
      },
    }
  );
};

const getTenantList = () => {
  getAgentList({ currentPage: 0, pageSize: 999 }).then(
    (res: Record<string, any>) => {
      if (res.success) {
        tenantOption.value = res.data?.list.map((item: Record<string, any>) => {
          return {
            label: item?.name,
            value: item?.id,
          };
        });
      }
    }
  );
};

// 多选
// const selectionChange = (val: any) => {
//   selectionData.value = val;
// };

const currentChange = (val: number) => {
  pageObj.pageNo = val;
  getList();
};

const sizechange = (val: number) => {
  pageObj.pageSize = val;
  getList(2);
};

onMounted(() => {
  getList();
  getTenantList();
});
</script>

<style lang="scss" scoped>
.table_box_wrapper {
  padding-top: 10px;
  margin-top: 15px;
  background-color: #fff;

  .allocation_app {
    padding: 12px 0 5px 10px;
  }
}

.table_box {
  padding: 10px;
  border-radius: 4px;

  .movie_box {
    display: flex;
    align-items: center;

    img {
      width: 72px;
      height: 108px;
      margin-right: 12px;
    }
  }
}
</style>
